package com.example.mypplication.sortlist.newsortlist


import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.mypplication.R

class ContactListAdapter : RecyclerView.Adapter<ContactListAdapter.ViewHolder>() {

    var isCheckMode: Boolean = false
        set(value) {
            field = value
            notifyDataSetChanged()
        }

    var onItemClickListener: ((SortModel) -> Unit)? = null
    private var contacts: List<SortModel> = emptyList()

    fun submitList(newList: List<SortModel>) {
        contacts = newList
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_contact, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val contact = contacts[position]

        // 显示/隐藏字母标题
        if (position == getPositionForSection(getSectionForPosition(position))) {
            holder.letterHeader.visibility = View.VISIBLE
            holder.letterHeader.text = contact.sortLetters
        } else {
            holder.letterHeader.visibility = View.GONE
        }

        // 设置联系人名称
        holder.nameText.text = contact.name

        // 设置性别图标
        holder.genderIcon.setImageResource(
            if (contact.sex == 0) R.drawable.boy else R.drawable.girl
        )

        // 设置选择状态
        if (isCheckMode) {
            holder.checkIcon.visibility = View.VISIBLE
            holder.checkIcon.setImageResource(
                if (contact.isChecked) R.drawable.round_checked else R.drawable.round_unchecked
            )
        } else {
            holder.checkIcon.visibility = View.GONE
        }

        // 设置点击事件
        holder.itemView.setOnClickListener {
            onItemClickListener?.invoke(contact)
        }
    }

    override fun getItemCount() = contacts.size

    fun getSectionForPosition(position: Int): Int {
        return contacts[position].sortLetters[0].toInt()
    }

    fun getPositionForSection(section: Int): Int {
        for (i in contacts.indices) {
            if (contacts[i].sortLetters[0].toInt() == section) {
                return i
            }
        }
        return -1
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val letterHeader: TextView = itemView.findViewById(R.id.letter_header)
        val nameText: TextView = itemView.findViewById(R.id.name_text)
        val genderIcon: ImageView = itemView.findViewById(R.id.gender_icon)
        val checkIcon: ImageView = itemView.findViewById(R.id.check_icon)
    }
}